<template>
  <div id="app">
    <el-card>
      <el-form :model="formData" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据编码">
              <el-input
                v-model="formData.billCode"
                placeholder="请输入单据编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务类型">
              <el-select
                v-model="formData.businessType"
                placeholder="请选择业务类型"
              >
                <el-option label="零部件" value="零部件"></el-option>
                <el-option label="原材料" value="原材料"></el-option>
                <el-option label="五金" value="五金"></el-option>
                <!-- 可添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用料需求">
              <el-select
                v-model="formData.materialDemand"
                placeholder="请选择用料需求"
              >
                <el-option label="订单用料" value="订单用料"></el-option>
                <!-- 可添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划单号">
              <el-input
                v-model="formData.planOrderNo"
                placeholder="请输入计划单号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据日期">
              <el-date-picker
                v-model="formData.billDate"
                type="date"
                placeholder="选择单据日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作员">
              <el-input
                v-model="formData.operator"
                placeholder="请输入操作员"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务部门">
              <el-select
                v-model="formData.businessDepartment"
                placeholder="请选择部门"
              >
                <el-option label="总经办" value="总经办"></el-option>
                <el-option label="采购部" value="采购部"></el-option>
                <el-option label="市场部" value="市场部"></el-option>
                <el-option label="销售部门" value="销售部门"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售单号">
              <el-input
                v-model="formData.salesOrderNo"
                placeholder="请输入销售单号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据状态">
              <el-select
                v-model="formData.billStatus"
                placeholder="请选择单据状态"
              >
                <el-option label="开立" value="开立"></el-option>
                <el-option label="审核" value="审核"></el-option>
                <!-- 可添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核员">
              <el-input
                v-model="formData.auditor"
                placeholder="请输入审核员"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务人员">
              <el-select
                v-model="formData.businessPerson"
                placeholder="请选择业务人员"
              >
                <el-option label="张建" value="张建"></el-option>
                <el-option label="杨娟" value="杨娟"></el-option>
                <el-option label="王守林" value="王守林"></el-option>
                <el-option label="赵构" value="赵构"></el-option>
                <el-option label="杨彪" value="杨彪"></el-option>
                <!-- 可添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售员">
              <el-input
                v-model="formData.salesPerson"
                placeholder="请输入销售员"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务状态">
              <el-select
                v-model="formData.businessStatus"
                placeholder="请选择业务状态"
              >
                <el-option label="正常" value="正常" />
                <el-option label="挂起" value="挂起" />
                <el-option label="手工关闭" value="手工关闭" />
                <el-option label="系统关闭" value="系统关闭" />
                <!-- 可添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核日期">
              <el-date-picker
                v-model="formData.auditDate"
                type="date"
                placeholder="选择审核日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注信息">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注信息"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单交期">
              <el-date-picker
                v-model="formData.orderDeliveryDate"
                type="date"
                placeholder="选择订单交期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="物料编码">
              <el-input
                v-model="formData.materialCode"
                placeholder="请输入物料编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料名称">
              <el-input
                v-model="formData.materialName"
                placeholder="请输入物料名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量">
              <el-input
                v-model="formData.quantity"
                placeholder="请输入数量"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: right; margin-top: 20px">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="get">返回</el-button>
        <el-button type="success">审核</el-button>
        <el-button type="warning">反审核</el-button>
        <el-button>收起</el-button>
      </div>
    </el-card>
    <el-card class="material-info-card">
      <div class="material-header">
        <span>物料信息</span>
        <el-button
          type="primary"
          @click="openProductSelector"
          class="action-button"
          >引入</el-button
        >
      </div>
      <el-table :data="dialogProductList" border>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="modelSpec" label="型号规格"></el-table-column>
        <el-table-column prop="mainUnit" label="主计量"></el-table-column>
        <el-table-column prop="requiredDate" width="140px" label="需求日期">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.requiredDate"
              type="date"
              placeholder="需求日期"
              value-format="YYYY-MM-DD"
              class="demand-date-picker"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="demandquantity" label="需求数量">
          <template #default="scope">
            <el-input
              v-model="scope.row.demandquantity"
              placeholder="输入数量"
              type="number"
            ></el-input> </template
        ></el-table-column>
        <el-table-column prop="num" label="可用量">0.0</el-table-column>
        <el-table-column prop="procurementNum" label="采购数量">
          <template #default="scope">
            <el-input
              v-model="scope.row.procurementNum"
              placeholder="输入数量"
              type="number"
            ></el-input> </template
        ></el-table-column>
        <el-table-column
          prop="procurementNum"
          label="已订数量"
        ></el-table-column>
        <el-table-column prop="procurementInstructions" label="采购说明">
          <template #default="scope">
            <el-input
              v-model="scope.row.procurementInstructions"
              placeholder="输入"
            ></el-input> </template
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" link @click="deleteProduct(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
  <el-dialog
    title="选择物料"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <div class="material-select-page">
      <div class="search-bar">
        <el-input
          placeholder="请输入分类名称"
          v-model="searchCategory"
          prefix-icon="el-icon-search"
        ></el-input>
        <el-input placeholder="物料编码" v-model="searchCode"></el-input>
        <el-input placeholder="物料名称" v-model="searchName"></el-input>

        <el-button>连选</el-button>
      </div>
      <div class="main-content">
        <el-table
          @selection-change="handleSelectionChange"
          :data="materialList"
          border
          style="width: 800px"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column
            prop="materialCode"
            label="物料编码"
            width="180"
          ></el-table-column>
          <!-- 修改为正确的属性名 -->
          <el-table-column
            prop="materialName"
            label="物料名称"
            width="180"
          ></el-table-column>
          <!-- 修改为正确的属性名 -->
          <el-table-column
            prop="modelSpec"
            label="型号规格"
            width="180"
          ></el-table-column>
          <!-- 修改为正确的属性名 -->
          <el-table-column
            prop="mainUnit"
            label="主计量"
            width="120"
          ></el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="form1.PageIndex"
          v-model:page-size="form1.PageSize"
          :page-sizes="[1, 3, 15, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="form1.TotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <br />
      <div class="button-group">
        <el-button @click="closeDialog" class="action-button"> 关闭 </el-button>
        <el-button
          type="primary"
          @click="confirmSelection"
          class="action-button"
        >
          选择
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
const dialogSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};
const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    dialogProductList.value.push({
      materialCode: selectedProduct.materialCode,
      materialName: selectedProduct.materialName,
      modelSpec: selectedProduct.modelSpec,
      mainUnit: selectedProduct.mainUnit,
    });
  });
  closeDialog();
};
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
//分页
const handleSizeChange = (newSize: number) => {
  form1.PageSize = newSize;
  searchProducts();
};
//分页
const handleCurrentChange = (newPage: number) => {
  form1.PageIndex = newPage; // 正确更新页码
  searchProducts();
};
// 对话框可见性
const dialogVisible = ref(false);
const closeDialog = () => {
  dialogVisible.value = false;
  dialogProductList.value.forEach((row) => {
    row._checked = false;
  });
};

// 物料列表数据
const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = dialogProductList.value.indexOf(product);
      if (index !== -1) {
        dialogProductList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};
// 物料表格数据
const dialogProductList = ref([]);
const materialList = ref([]);
// 搜索条件
const searchCategory = ref("");
const searchCode = ref("");
const searchName = ref("");

// 打开物料选择对话框
const openProductSelector = async () => {
  dialogVisible.value = true;
  searchProducts();
};
const searchProducts = () => {
  axios
    .get("http://localhost:5202/api/Log/GetERPMaterials/GetERPMaterials", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      materialList.value = res.data.data.list;
      form1.TotalCount = res.data.data.totalCount;
      form1.PageCount = res.data.data.PageCount;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
// 表单数据
const formData = ref({
  billCode: "",
  businessType: "零部件",
  materialDemand: "",
  planOrderNo: "",
  billDate: dayjs().format("YYYY-MM-DD"),
  operator: "陈平安",
  businessDepartment: "",
  salesOrderNo: "",
  billStatus: "开立",
  auditor: "陈平安",
  businessPerson: "",
  salesPerson: "",
  businessStatus: "正常",
  auditDate: "2025-04-29T03:28:19.117Z",
  remark: "",
  orderDeliveryDate: dayjs().format("YYYY-MM-DD"),
  materialCode: (route.query.materialCode as string) || "",
  materialName: "",
  quantity: "",
});
// 调用后端接口获取物料数据
const submitForm = async () => {
  // 构造符合后端要求的数据结构
  const payload = {
    ...formData.value,
    // 物料列表需要转换数据结构
    Products: dialogProductList.value.map((item) => ({
      MaterialCode: item.materialCode,
      MaterialName: item.materialName,
      ModelSpec: item.modelSpec,
      MainUnit: item.mainUnit,
      Demandquantity: Number(item.demandquantity) || 0, // 确保转换为数字类型
      ProcurementNum: Number(item.procurementNum) || 0,
      requiredDate: item.requiredDate,
      ProcurementInstructions: item.procurementInstructions,
    })),
  };
  console.log(payload);
  try {
    const res = await axios.post(
      "http://localhost:5027/api/Log/UpdateProcurement",
      payload,
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    if (res.data.code === 300) {
      ElMessage.success("修改成功");
      router.push("/GetProcurement");
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    ElMessage.error("请求失败，请检查控制台");
    console.error("API Error:", error);
  }
};
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    // 生成12位数字
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
const handleView = () => {
  const sellStringCode = route.query.materialCode; // 改为通过销售单号查询

  if (!sellStringCode) {
    console.log("未获取到销售单号");
    return;
  }

  // 统一使用form.value来管理表单数据
  formData.value.materialCode = sellStringCode as string;

  // 获取入库单基本信息
  axios
    .get(`http://localhost:5202/api/Log/EditProcurement`, {
      params: {
        MaterialCode: sellStringCode, // 确保后端API接收这个参数
      },
    })
    .then((res) => {
      if (res.data.data && res.data.data.length > 0) {
        const basicInfo = res.data.data[0];
        Object.assign(formData.value, {
          ...basicInfo,
        });
      }
    });

  // 获取产品信息
  axios
    .get(`http://localhost:5202/api/Log/EditProcurementMateials`, {
      params: {
        MaterialCode: sellStringCode, // 确保后端API改为通过销售单号查询
      },
    })
    .then((res) => {
      dialogProductList.value = res.data.data.map((item) => ({
        procurementMateialsId: item.procurementMateialsId,
        materialCode: (route.query.materialCode as string) || "",
        Demandquantity: Number(item.demandquantity),
        materialName: item.materialName,
        mainUnit: item.mainUnit,
        modelSpec: item.modelSpec,
        procurementNum: item.procurementNum,
        requiredDate: item.requiredDate,
        procurementInstructions: item.procurementInstructions,
      }));
    });
};
onMounted(() => {
  handleView();
});
const get = () => {
  router.push("/GetProcurement");
};
</script>

<style scoped>
#app {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 卡片样式优化 */
.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  border: none;
}

.purchase-plan-card {
  margin-bottom: 20px;
}

/* 表单容器间距优化 */
.form-container {
  margin-bottom: 20px;
}

/* 表单项标签样式 */
.el-form-item__label {
  color: #606266;
  font-weight: 500;
}

/* 输入框和选择器统一宽度 */
.el-input,
.el-select,
.el-date-editor {
  width: 100%;
}

/* 按钮容器优化 */
.button-container {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

/* 物料信息卡片头部 */
.material-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.demand-date-picker {
  width: 180px;
  margin-left: 15px;
}

/* 表格优化 */
.el-table {
  margin-top: 15px;
}

.el-table--border {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa !important;
  color: #303133;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

/* 对话框搜索栏 */
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-bar .el-input {
  flex: 1;
  max-width: 200px;
}
.el-form-item__label {
  text-align: right;
  color: #606266;
  font-weight: 500;
}
.el-input,
.el-select,
.el-date-editor {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.el-date-picker__input {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
/* 分页样式 */
.el-pagination {
  margin-top: 15px;
  justify-content: flex-end;
}

/* 操作按钮统一风格 */
.action-button {
  margin-left: 10px;
  min-width: 80px;
}

/* 响应式优化 */
@media (max-width: 1200px) {
  .el-col {
    margin-bottom: 15px;
  }

  .el-col:last-child {
    margin-bottom: 0;
  }

  .el-col-6 {
    width: 100%;
    max-width: 100%;
  }
}
</style>